package com.battle.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.entity.CaseBaseInfo;
import com.battle.pojo.entity.StudyPlan;
import com.battle.pojo.entity.StudyPlanUser;
import com.battle.pojo.entity.StudyUser;
import com.battle.pojo.enums.StudyPlanTypeEnum;
import com.battle.pojo.param.studyPlanUser.*;
import com.battle.pojo.vo.studyPlanUser.*;
import com.battle.pojo.dto.studyPlanUser.*;
import com.battle.service.repository.in.CaseBaseInfoRepository;
import com.battle.service.repository.in.StudyPlanRepository;
import com.battle.service.repository.in.StudyPlanUserRepository;
import com.battle.service.repository.in.StudyUserRepository;
import com.battle.service.service.in.StudyPlanUserService;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.glassfish.jaxb.core.v2.TODO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：用户学习进度服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class StudyPlanUserServiceImpl implements StudyPlanUserService {

    private final StudyPlanUserRepository studyPlanUserRepository;
    private final StudyUserRepository studyUserRepository;
    private final StudyPlanRepository studyPlanRepository;
    private final CaseBaseInfoRepository caseBaseInfoRepository;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 用户学习完成的战例数
     */
    private final String STUDY_PLAN_USER = "study_plan_user";

    public StudyPlanUserServiceImpl(StudyPlanUserRepository studyPlanUserRepository, StudyUserRepository studyUserRepository, StudyPlanRepository studyPlanRepository, CaseBaseInfoRepository caseBaseInfoRepository, StringRedisTemplate stringRedisTemplate) {
        this.studyPlanUserRepository = studyPlanUserRepository;
        this.studyUserRepository = studyUserRepository;
        this.studyPlanRepository = studyPlanRepository;
        this.caseBaseInfoRepository = caseBaseInfoRepository;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    /**
     * 创建用户学习进度
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createStudyPlanUser(CreateStudyPlanUserParam param) {
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();

        //根据学习内容和学习时间查找学习计划，如果没有找到或者找到多个则报错
        List<StudyPlan> studyPlanList = studyPlanRepository.getStudyPlanList(param.getLearningTime(), param.getType(),null);
        if (CollectionUtil.isNotEmpty(studyPlanList)) {
            //每15秒调用一次接口
            Integer time=15;

            if (studyPlanList.size()>1) throw new BizException("同时间段同类型只允许存在一个学习计划");
            StudyPlan plan = studyPlanList.stream().findFirst().get();

            //查找用户学习计划
            StudyUser studyUser=new StudyUser();
            studyUser.setIsDelete(false);
            studyUser.setIsDisable(false);
            studyUser.setPlanId(plan.getId());
            studyUser.setUserId(param.getUserId());

            StudyUser studyUserEntity = studyUserRepository.getByEntity(studyUser);
            if (studyUserEntity==null){
                studyUserEntity=new StudyUser();
                studyUserEntity.setIsComplete(false);
                studyUserEntity.setLearningNumber(plan.getLearningNumber());
                studyUserEntity.setCompleteNumber(0);
                studyUserEntity.setId(IdGenerator.SNOW.generate());
                studyUserEntity.setUserId(param.getUserId());
                studyUserEntity.setPlanId(plan.getId());
                studyUserRepository.save(studyUserEntity);
            }

            //查找用户学习进度，如果没有说明是第一次学习
            StudyPlanUser planUser=new StudyPlanUser();
            planUser.setIsDelete(false);
            planUser.setIsDisable(false);
            planUser.setPlanId(plan.getId());
            planUser.setFid(param.getFid());
            planUser.setType(param.getType());

            StudyPlanUser byEntity = studyPlanUserRepository.getByEntity(planUser);
            if (byEntity==null){
                byEntity=new StudyPlanUser();
                BeanUtils.copyProperties(planUser,byEntity);
                BeanUtils.copyProperties(param,byEntity);

                if (param.getIsPdf()){
                    byEntity.setLearningTime(300);
                    byEntity.setIsComplete(true);
                    //更新一下学习完成数量
                    studyUserEntity.setCompleteNumber(studyUserEntity.getCompleteNumber()+1);
                    if (studyUserEntity.getLearningNumber()==studyUserEntity.getCompleteNumber()){
                        studyUserEntity.setIsComplete(true);
                    }
                    studyUserRepository.updateById(studyUserEntity);
                }else{
                    byEntity.setLearningTime(300);
                    byEntity.setIsComplete(false);
                }
                byEntity.setId(IdGenerator.SNOW.generate());
                byEntity.setLearningTime(byEntity.getLearningTime()+time);
                studyPlanUserRepository.save(byEntity);


            }else{
                byEntity.setLearningTime(byEntity.getLearningTime()+time);
                if (param.getIsPdf()){

                }else{
                    byEntity.setIsComplete(true);
                    //更新一下学习完成数量
                    studyUserEntity.setCompleteNumber(studyUserEntity.getCompleteNumber()+1);
                    if (studyUserEntity.getLearningNumber()==studyUserEntity.getCompleteNumber()){
                        studyUserEntity.setIsComplete(true);
                    }
                    studyUserRepository.updateById(studyUserEntity);
                }
                //超过5分钟
                if (byEntity.getLearningTime()>=300 && byEntity.getIsComplete()==false){
                    byEntity.setIsComplete(true);
                    //更新一下学习完成数量
                    studyUserEntity.setCompleteNumber(studyUserEntity.getCompleteNumber()+1);
                    if (studyUserEntity.getLearningNumber()==studyUserEntity.getCompleteNumber()){
                        studyUserEntity.setIsComplete(true);
                    }
                    studyUserRepository.updateById(studyUserEntity);
                }
                studyPlanUserRepository.updateById(byEntity);
            }
        }
    }

    /**
     * 修改用户学习进度
     *
     * @param param
     */
    @Override
    public void editStudyPlanUser(EditStudyPlanUserParam param) {
        Long id = param.getId();
        StudyPlanUser studyPlanUser = studyPlanUserRepository.getByIdCheck(id);
        BeanUtils.copyProperties(param, studyPlanUser);
        studyPlanUserRepository.edit(studyPlanUser);
    }

    /**
     * 移除用户学习进度
     *
     * @param id
     */
    @Override
    public void removeStudyPlanUser(Long id) {
        studyPlanUserRepository.removeById(id);
    }

    /**
     * 启动/禁用用户学习进度
     *
     * @param id
     */
    @Override
    public void enabledStudyPlanUser(Long id) {
        StudyPlanUser studyPlanUser = studyPlanUserRepository.getByIdCheck(id);
        studyPlanUser.setIsDisable(!studyPlanUser.getIsDisable());
        studyPlanUserRepository.edit(studyPlanUser);
    }

    /**
     * 根据用户和学习计划id获取学习进度
     * @param planId
     * @param userId
     * @return
     */
    @Override
    public List<GetStudyPlanUserVo> getStudyPlanUser(Long planId, Long userId) {
        List<GetStudyPlanUserVo> voList=new ArrayList<>();

        StudyPlan plan = studyPlanRepository.getByIdCheck(planId);

        StudyPlanUser planUser=new StudyPlanUser();
        planUser.setIsDelete(false);
        planUser.setIsDisable(false);
        planUser.setPlanId(planId);
        planUser.setUserId(userId);
        planUser.setType(plan.getType());

        List<StudyPlanUser> studyPlanUser = studyPlanUserRepository.getListByEntity(planUser);
        if (CollectionUtil.isNotEmpty(studyPlanUser)){
            List<Long> ids = studyPlanUser.stream().map(StudyPlanUser::getFid).distinct().collect(Collectors.toList());
            if (plan.getType().getId()== StudyPlanTypeEnum.tactics.getId()){
                //TODO 战术
            }else{
                Map<Long, CaseBaseInfo> map = caseBaseInfoRepository.getMap(ids);
                for (StudyPlanUser user : studyPlanUser) {
                    GetStudyPlanUserVo vo=new GetStudyPlanUserVo();
                    BeanUtils.copyProperties(user,vo);
                    if (CollectionUtil.isNotEmpty(map)){
                        CaseBaseInfo caseBaseInfo = map.get(user.getFid());
                        if (caseBaseInfo!=null){
                            vo.setCaseName(caseBaseInfo.getName());
                        }
                    }
                    voList.add(vo);
                }

            }
        }

        return voList;
    }

    /**
     * 获取用户学习进度 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetStudyPlanUserListVo> getStudyPlanUserList(GetStudyPlanUserListParam param) {
        SelectStudyPlanUserDto dto = new SelectStudyPlanUserDto();
        BeanUtils.copyProperties(param, dto);
        Page<GetStudyPlanUserListVo> page = studyPlanUserRepository.selectStudyPlanUser(dto);
        List<GetStudyPlanUserListVo> list = page.getRecords();
        //获取是否完成
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        Map<String, String> map = hash.entries(STUDY_PLAN_USER);
        for (GetStudyPlanUserListVo vo : list) {
            vo.setIsComplete(false);
            String numberValue = map.getOrDefault(vo.getPlanId().toString()+vo.getUserId().toString(), "0");
            Integer number = Integer.valueOf(numberValue);
            if (number==vo.getLearningNumber()){
                vo.setIsComplete(true);
            }
        }

        return new PageResult<>(list, page);

    }

    /**
     * 获取用户学习进度下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetStudyPlanUserDownListVo> getStudyPlanUserDownList(GetStudyPlanUserDownListParam param) {
        StudyPlanUser po = new StudyPlanUser();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
        }
        List<StudyPlanUser> studyPlanUserList = studyPlanUserRepository.getListByEntity(po);

        List<GetStudyPlanUserDownListVo> list = new ArrayList<>();
        for (StudyPlanUser studyPlanUser : studyPlanUserList) {
            GetStudyPlanUserDownListVo vo = new GetStudyPlanUserDownListVo();
            BeanUtils.copyProperties(studyPlanUser, vo);
            list.add(vo);
        }
        return list;
    }

}



